import {ref} from "vue";
import {changeRouter} from "../route/changeRouter.ts";
import {PostRequest} from "../axios/PostRequest.ts";
import {LOGIN_URL} from "../axios/loginRouting.ts";
import {mainStore} from "../store/store.ts";
import {storeToRefs} from "pinia";

export function useLogin() {
    const account = ref<string>('')
    const password = ref<string>('')
    const bgImg = ref<string>("/assets/login_main.png")

    account.value = localStorage.getItem("xioa_system_account") as string ?? ""
    password.value = localStorage.getItem("xioa_system_password") as string ?? ""

    // const router = useRouter()
    const store = mainStore()

    function setStoreUser(value: any) {
        const {account} = storeToRefs(store)
        account.value = value;
    }

    async function AutoLogin(): Promise<{ result: boolean }> {
        let account = localStorage.getItem('xioa_system_account') as string;
        let password = localStorage.getItem('xioa_system_password') as string;
        let res = await PostRequest(LOGIN_URL, {account: account, password: password})

        if (res.data.success) {
            changeRouter(res.data.post);
            const {
                userName
            } = storeToRefs(store)
            setStoreUser(account);
            userName.value = res.data.data.name;
            return {result: res.data.success}
        }
        return {result: false}
    }

    async function Login(): Promise<{ result: boolean, message: string }> {
        let zh = account.value
        let res = await PostRequest(LOGIN_URL, {account: account.value, password: password.value})
        if (res.data.success) {
            localStorage.setItem("xioa_system_account", zh)
            localStorage.setItem("xioa_system_password", password.value)
            changeRouter(res.data.post);
            const {
                userName
            } = storeToRefs(store)
            setStoreUser(account.value);
            userName.value = res.data.data.name;

            return {result: res.data.success, message: res.data.message};
        }
        return {result: false, message: res.data.message};
    }

    return {
        account,
        password,
        Login,
        bgImg, AutoLogin
    }
}